import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from 'element-plus'
import MiAlert from "@/components/MiAlert/MiAlert";


interface HttpReslt<T = null> {
    code: 200 | 199 | 404 | 401 | 500;
    data: T;
    msg: string;
}



function http<T, R>(options: AxiosRequestConfig<T>): Promise<R> {

    // console.log(proxy)
    const defaultHeaders = { Authorization: sessionStorage.getItem("token") };
    options.headers = { ...defaultHeaders, ...options.headers || {} }
    return axios(options)
        .then((response: AxiosResponse<HttpReslt<R>>) => {
            const { status, data, statusText } = response;
            if (status === 200) return data;
            else throw new Error(statusText)
        })
        .then((response: HttpReslt<R>) => {
            const { code, data, msg } = response;
            switch (code) {
                case 200: return data;
                case 199:
                case 404:
                case 401:
                case 500:
                    throw new Error(msg);
                default:
                    const a: never = code
                    throw new Error(msg)
            }
        })
        .catch((e) => {
            // ElMessage.error(e.message)
           MiAlert({
                title: "提示",
                text: e.message
            })
            throw e;

        })
}

export default http;